package com.mylg.craw.house.lbs.gaode;

import com.alibaba.excel.EasyExcel;
import com.fasterxml.jackson.core.type.TypeReference;
import com.mylg.craw.house.lbs.gaode.bean.*;
import com.mylg.craw.house.util.JacksonUtils;
import jakarta.annotation.Resource;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestClient;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * https://lbs.amap.com/api/webservice/guide/api/district
 */
@Service
public class LbsGaodeCommand implements CommandLineRunner {
    private static final String KEY = "179da5a2c63a58f7b9d835ae74db3eb4";

    private static final String URL = "https://restapi.amap.com/v3/config/district";

    @Resource
    private RestClient restClient;

    @Override
    public void run(String... args) throws Exception {
        geocode("/Users/jiangqiaonan/opensource/personal/craw-hourse/school/学校名录.xlsx");
        System.exit(0);
    }

    /**
     * 详细地址转经纬度
     */
    private void geocode(String filename) {
        List<SchoolLocation> list = EasyExcel.read(filename).head(SchoolLocation.class).doReadAllSync();
        String baseUrl = "https://restapi.amap.com/v3/geocode/geo?key=%s&address=%s&city=0371";
        if (list.isEmpty()) {
            return;
        }

        for (SchoolLocation item : list) {
            if (StringUtils.isEmpty(item.getAddress()) || !StringUtils.isEmpty(item.getLocation())) {
                continue;
            }
            String url = String.format(baseUrl, KEY, item.getAddress());
            String json = restClient.get().uri(url).retrieve().body(String.class);
            GeoCodeRes geoCodeRes = JacksonUtils.readValue(json, GeoCodeRes.class);
            if (geoCodeRes == null) {
                continue;
            }
            item.setLocation(geoCodeRes.computeLocation());
        }

        Map<String, List<SchoolLocation>> groups = list.stream().collect(Collectors.groupingBy(SchoolLocation::getType));

        System.out.println(JacksonUtils.writeValueAsString(groups));
    }


    /**
     * 查询地铁站
     */
    private void querySubwayGps() {
        int batchSize = 10;
        int page = 1;

        List<SubWayStation> stations = new ArrayList<>();

        do {
            String url = String.format("%s?types=%s&region=%s&key=%s&city_limit=%s&page_size=%d&page_num=%d",
                    "https://restapi.amap.com/v5/place/text",
                    150500, //地铁站
                    "0371",//郑州
                    KEY, "true", batchSize, page);
            String res = restClient.get().uri(url).retrieve().body(String.class);
            PoiV2List poiV2List = JacksonUtils.readValue(res, PoiV2List.class);
            if (poiV2List == null || CollectionUtils.isEmpty(poiV2List.getPois())) {
                break;
            }
            List<PoiV2Item> list = poiV2List.getPois();
            for (PoiV2Item item : list) {
                SubWayStation station = item.pickUp();
                String line = station.getLine();
                if (line.contains(";")) {
                    String[] splits = line.split(";");
                    station.setRelationLines(new ArrayList<>());
                    for (int i = 1; i < splits.length; i++) {
                        station.getRelationLines().add(splits[i]);
                    }
                    station.setLine(splits[0]);
                }
                stations.add(station);
            }

            if (list.size() < batchSize) {
                break;
            }

            page += 1;
        } while (true);

        System.out.println("输出结果——————————————————————————————————————————————");
        System.out.println(JacksonUtils.writeValueAsString(stations));
    }


    //郑州各个区县的code码
    //https://lbs.amap.com/api/webservice/guide/api-advanced/newpoisearch
    private void queryZzDistricts() {
        String url = String.format("%s?key=%s&keywords=%s&subdistrict=1&extensions=all", URL, KEY, "郑州");
        String res = restClient.get().uri(url).retrieve().body(String.class);
        RegionRes regionRes = JacksonUtils.readValue(res, RegionRes.class);
        System.out.println(regionRes);
    }

    /**
     * 郑州的区县的边界
     */
    private void queryZzPolyLine() {
        final String JSON = "[{\"adcode\": \"410185\",\"center\": \"113.05056,34.454877\",\"citycode\": \"0371\",\"districts\": [],\"level\": \"district\",\"name\": \"登封市\"},{\"adcode\": \"410105\",\"center\": \"113.6603,34.800415\",\"citycode\": \"0371\",\"districts\": [],\"level\": \"district\",\"name\": \"金水区\"},{\"adcode\": \"410122\",\"center\": \"113.975798,34.720535\",\"citycode\": \"0371\",\"districts\": [],\"level\": \"district\",\"name\": \"中牟县\"},{\"adcode\": \"410184\",\"center\": \"113.74024,34.396479\",\"citycode\": \"0371\",\"districts\": [],\"level\": \"district\",\"name\": \"新郑市\"},{\"adcode\": \"410181\",\"center\": \"113.022354,34.748207\",\"citycode\": \"0371\",\"districts\": [],\"level\": \"district\",\"name\": \"巩义市\"},{\"adcode\": \"410108\",\"center\": \"113.617055,34.867994\",\"citycode\": \"0371\",\"districts\": [],\"level\": \"district\",\"name\": \"惠济区\"},{\"adcode\": \"410182\",\"center\": \"113.383385,34.7866\",\"citycode\": \"0371\",\"districts\": [],\"level\": \"district\",\"name\": \"荥阳市\"},{\"adcode\": \"410106\",\"center\": \"113.309185,34.803514\",\"citycode\": \"0371\",\"districts\": [],\"level\": \"district\",\"name\": \"上街区\"},{\"adcode\": \"410102\",\"center\": \"113.612966,34.74828\",\"citycode\": \"0371\",\"districts\": [],\"level\": \"district\",\"name\": \"中原区\"},{\"adcode\": \"410183\",\"center\": \"113.390932,34.540216\",\"citycode\": \"0371\",\"districts\": [],\"level\": \"district\",\"name\": \"新密市\"},{\"adcode\": \"410104\",\"center\": \"113.677446,34.754436\",\"citycode\": \"0371\",\"districts\": [],\"level\": \"district\",\"name\": \"管城回族区\"},{\"adcode\": \"410103\",\"center\": \"113.640177,34.724138\",\"citycode\": \"0371\",\"districts\": [],\"level\": \"district\",\"name\": \"二七区\"}]";
        List<District> districts = JacksonUtils.readValue(JSON, new TypeReference<List<District>>() {
        });
        List<District> list = new ArrayList<>();
        for (District district : districts) {
            String url = String.format("%s?key=%s&keywords=%s&subdistrict=0&extensions=all", URL, KEY, district.getAdCode());
            String res = restClient.get().uri(url).retrieve().body(String.class);
            RegionRes regionRes = JacksonUtils.readValue(res, RegionRes.class);
            if (regionRes != null && !CollectionUtils.isEmpty(regionRes.getDistricts())) {
                list.add(regionRes.getDistricts().get(0));
            }
        }
        System.out.println(JacksonUtils.writeValueAsString(list));
    }


}
